import type { permItem } from '@/store/type'
import { defineStore } from 'pinia'
import { getMenu } from '@/apis/common/index'

export const usePermissionStore = defineStore(
  'permissionStore',
  () => {
    const permList = ref<permItem[]>([])
    const menuTree = ref<permItem[]>([])
    const isGenerated = ref<boolean>(false)

    // 生成菜单树
    function generateMenu() {
      menuTree.value = permList.value
    }
    function updatePermission(perm: Array<permItem>) {
      permList.value = perm
    }

    // 初始化权限
    async function getPermission() {
      const { data } = await getMenu({}).catch(() => {
        return Promise.reject(new Error('获取菜单失败'))
      }) as any
      updatePermission(data)
      generateMenu()
      return Promise.resolve(data)
    }
    // 更新路由是否生成状态
    function updateIsGenerated(_isGenerated: boolean) {
      isGenerated.value = _isGenerated
    }
    return {
      permList,
      updatePermission,
      getPermission,
      isGenerated,

      menuTree,
      generateMenu,
      updateIsGenerated,
    }
  },
)
